package com.flowplan.auth.controller;

import com.flowplan.auth.dto.LoginRequest;
import com.flowplan.auth.dto.LoginResponse;
import com.flowplan.auth.service.AuthService;
import com.flowplan.auth.service.UserService;
import com.flowplan.common.dto.ApiResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * 认证控制器
 * 
 * @author FlowPlan Team
 */
@Slf4j
@RestController
@RequestMapping("/auth")
public class AuthController {
    
    @Autowired
    private AuthService authService;
    
    @Autowired
    private UserService userService;
    
    @Value("${jwt.header}")
    private String tokenHeader;
    
    @Value("${jwt.prefix}")
    private String tokenPrefix;
    
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public ResponseEntity<ApiResponse<LoginResponse>> login(@Valid @RequestBody LoginRequest loginRequest) {
        try {
            LoginResponse response = authService.login(loginRequest);
            return ResponseEntity.ok(ApiResponse.success("登录成功", response));
        } catch (Exception e) {
            log.error("登录失败: {}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error(400, "登录失败: " + e.getMessage()));
        }
    }
    
    /**
     * 刷新Token
     */
    @PostMapping("/refresh")
    public ResponseEntity<ApiResponse<LoginResponse>> refreshToken(HttpServletRequest request) {
        try {
            String refreshToken = getTokenFromRequest(request);
            if (refreshToken == null) {
                return ResponseEntity.badRequest()
                        .body(ApiResponse.error(400, "刷新Token不能为空"));
            }
            
            LoginResponse response = authService.refreshToken(refreshToken);
            return ResponseEntity.ok(ApiResponse.success("Token刷新成功", response));
        } catch (Exception e) {
            log.error("Token刷新失败: {}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error(400, "Token刷新失败: " + e.getMessage()));
        }
    }
    
    /**
     * 用户登出
     */
    @PostMapping("/logout")
    public ResponseEntity<ApiResponse<Void>> logout(HttpServletRequest request) {
        try {
            String token = getTokenFromRequest(request);
            if (token != null) {
                authService.logout(token);
            }
            return ResponseEntity.ok(ApiResponse.success("登出成功"));
        } catch (Exception e) {
            log.error("登出失败: {}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error(400, "登出失败: " + e.getMessage()));
        }
    }
    
    /**
     * 验证Token
     */
    @GetMapping("/validate")
    public ResponseEntity<ApiResponse<Boolean>> validateToken(HttpServletRequest request) {
        try {
            String token = getTokenFromRequest(request);
            if (token == null) {
                return ResponseEntity.ok(ApiResponse.success("Token验证结果", false));
            }
            
            boolean isValid = authService.validateToken(token);
            return ResponseEntity.ok(ApiResponse.success("Token验证结果", isValid));
        } catch (Exception e) {
            log.error("Token验证失败: {}", e.getMessage());
            return ResponseEntity.ok(ApiResponse.success("Token验证结果", false));
        }
    }
    
    /**
     * 获取当前用户信息
     */
    @GetMapping("/me")
    public ResponseEntity<ApiResponse<LoginResponse.UserInfo>> getCurrentUser(HttpServletRequest request) {
        try {
            String token = getTokenFromRequest(request);
            if (token == null) {
                return ResponseEntity.badRequest()
                        .body(ApiResponse.error(400, "Token不能为空"));
            }
            
            // 从Token中提取用户ID
            Long userId = authService.getUserIdFromToken(token);
            if (userId == null) {
                return ResponseEntity.badRequest()
                        .body(ApiResponse.error(400, "无法从Token中提取用户信息"));
            }
            
            // 获取用户信息（会自动缓存到Redis）
            LoginResponse.UserInfo userInfo = userService.getUserInfoById(userId);
            
            return ResponseEntity.ok(ApiResponse.success("获取用户信息成功", userInfo));
        } catch (Exception e) {
            log.error("获取用户信息失败: {}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error(400, "获取用户信息失败: " + e.getMessage()));
        }
    }
    
    /**
     * 从请求中提取Token
     */
    private String getTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader(tokenHeader);
        if (bearerToken != null && bearerToken.startsWith(tokenPrefix)) {
            return bearerToken.substring(tokenPrefix.length());
        }
        return null;
    }
}